#include"udpServer.hpp"
#include<sys/types.h>
#include<sys/socket.h>
#include<cstring>
#include<cstdlib>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"common.hpp"
// ./client_udp serverip serverport

int main(int args, char* argv[])
{
    if (args != 3)
    {
        std::cerr << "Usage" << argv[0] << "serverip severport" << std::endl;
        die(usage_error);
    } 
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    // 创建socket
    int socket = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (socket < 0) 
    {
        std::cerr << "socket error" << std::endl;
        die(socket_error);
    }

    // 1.1 填充server信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = ::htons(serverport);
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());
    // 2.client done
    while(true)
    {
        std::cout << "Please enter#";
        std::string message;
        std::getline(cin, message);
        // cin.ignore();
    // zdl:: 个护短必须要要有自己的ip和端口， 
    // 到那时客户端不需要自己显示的调用而
    // 是客户端首次sendto info时，有os自动显示调用bind
    // 1 how to understand client bind automaticaly (random)一个端口号只被一个进程bind
    // 2. 如何理解server要显示的bind  服务器的端口号必须要稳定，服务器的端口号必须是总所周知的
        int n = ::sendto(socket, message.c_str(), 
        message.size(), 0, conv(&server), sizeof(server));
        (void)n;
        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        n = ::recvfrom(socket, buffer, sizeof(buffer) - 1, 0, conv(&temp), &len);

        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }
    return 0;
}